﻿using CommonUtils;
using System;
using System.Data;
using System.Data.SQLite;
using System.IO;

namespace DatabaseService.DatabaseService
{
    public class SqliteDatabaseInfoDAO : IDatabaseInfoDAO
    {
        private string connStr;
        private string dbver;
        private int timeout = 2000;
        private BaseCharset charset;

        public SqliteDatabaseInfoDAO()
        {
            try
            {
                //string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DatabaseService\\Sqlite\\scanner.db");
                string path = PathManager.AppConfigDbPath;
                //需要配置链接字符串
                connStr = $"Data Source={path}";//;password=123456;";
                //connStr = $"Data Source={path};password=DYJ170119;";
            }
            catch (Exception exc)
            {
                throw new Exception("数据库文件不存在或格式不对！");
            }
            Init_data();
        }

        public void Init_data()
        {
            try
            {
                DataTable dt = new DataTable();
                using (SQLiteConnection connection = new SQLiteConnection(connStr))
                {
                    connection.Open();
                    SQLiteDataAdapter dataAdapter = new SQLiteDataAdapter("select sqlite_version()", connection);
                    dataAdapter.Fill(dt);
                    dataAdapter.Dispose();
                }
                dbver = dt.Rows[0][0].ToString() ?? "8.0.3";
            }
            catch(Exception ex)
            {
                dbver = "";
            }
            charset = new Charset803Entity();
        }

        /// <summary>
        /// 获取数据库连接字符串
        /// </summary>
        /// <returns></returns>
        public string GetConnectionString()
        {
            return this.connStr ?? "";
        }

        /// <summary>
        /// 获取数据库版本
        /// </summary>
        /// <returns></returns>
        public string GetDbVerson()
        {
            return this.dbver ?? "";
        }

        /// <summary>
        /// 获取转码实例
        /// </summary>
        /// <returns></returns>
        public BaseCharset GetCharset()
        {
            return this.charset;
        }

        /// <summary>
        /// 获取数据库连接超时时间
        /// </summary>
        /// <returns></returns>
        public int GetTimeout()
        {
            return this.timeout;
        }
    }
}
